<?php

use Biz\model\brandActivity\BlindBoxActivity as mBlindBoxActivity;
use Biz\model\brandActivity\BlindBoxLottery as mBlindBoxLottery;
use Biz\model\brandActivity\BlindBoxLotteryConsignee as mBlindBoxLotteryConsignee;
use Biz\model\brandIndex\BrandMsg;
use Biz\service\BrandIndex;
use Doraemon\tools\BlockType;
use Biz\service\brand\BlindBoxActivity;

/**
 * 保存收货地址
 */
class SaveAddressAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;

    //参数校验-规则
    public const VALIDATOR_RULES = [
        'consignee_name' => 'require',
        'consignee_mobile' => 'require',
        'area_code' => 'require|integer',
        'consignee_address' => 'require',
    ];

    public function main()
    {
        $lotteryId = $this->getRequest()->getPost('lottery_id', 0);
        if (!$lotteryId) {
            throw  new \Exception('参数错误');
        }
        $lotteryInfo = mBlindBoxLottery::getByWhere(['id' => $lotteryId]);
        if (empty($lotteryInfo)) {
            throw new \Exception('不存在的中奖信息');
        }
        $consigneeName = $this->params['consignee_name'];
        $consigneeMobile = $this->params['consignee_mobile'];
        $areaCode = $this->params['area_code'];
        $consigneeAddress = $this->params['consignee_address'];
        $areaName = \Hhz\AdministrativeRegion\Region::getAreaDetailByCode($areaCode);
        $consigneeInfo = mBlindBoxLotteryConsignee::getByWhere(['lottery_id' => $lotteryId]);
        if ($consigneeInfo) {
            mBlindBoxLotteryConsignee::updateData([
                'consignee_name' => $consigneeName,
                'consignee_mobile' => $consigneeMobile,
                'area_code' => $areaCode,
                'area_name' => $areaName,
                'consignee_address' => $consigneeAddress
            ], ['lottery_id' => $lotteryId]);
        } else {
            mBlindBoxLotteryConsignee::insertData([
                'lottery_id' => $lotteryId,
                'consignee_name' => $consigneeName,
                'consignee_mobile' => $consigneeMobile,
                'area_code' => $areaCode,
                'area_name' => $areaName,
                'consignee_address' => $consigneeAddress
            ]);
            $activityId = $lotteryInfo['activity_id'];
            $activityInfo = mBlindBoxActivity::getInfoById($activityId);
            $activityTitle = $activityInfo['title'];
            $msg = '你的 ' . $activityTitle . ' 超级盲盒活动有用户已抽中奖品，请点击此处查看';
            BrandIndex::writeMsg($activityInfo['brand_id'], BrandMsg::MSG_TYPE_PASS, BrandMsg::MSG_SOURCE_BLIND_BOX,
                $msg, BlockType::TYPE_BLIND_BOX_LOTTERY, $activityId);
        }

        BlindBoxActivity::shippingRemind($lotteryInfo['activity_id']);

        $this->setSuccess();
    }
}